package com.zp.testpractice.learnTest.dagger;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.zp.testpractice.learnTest.mockito.PasswordValidator;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * @author izp on 2017/11/11.
 * 用于统一提供依赖dependcies，用Module注解，然后Compoment来扫描它
 */
@Module
public class AppModule {
    /**
     * 用final来修饰context好么？
     */
    private final Context mContext;

    public AppModule(Context context) {
        this.mContext = context;
    }

    /**
     * Provides注解表明他会生成一个dependency,对象供别人使用
     * Singleton注解表明这是一个单例，IO相关的貌似都是单例
     * @return
     */
    @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient() {
        OkHttpClient okhttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();
        return okhttpClient;
    }

    @Provides
    @Singleton
    public Retrofit provideRetrofit(OkHttpClient okhttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(okhttpClient)
                .baseUrl("https://api.github.com")
                .build();
        return retrofit;
    }

    /**
     * 只要是在Module里面，如果要传入参数的会自动在provider里面找到相应的对象
     * 这个是Retrofit的直接使用对象
     * @param retrofit
     * @return
     */
    @Provides
    @Singleton
    public UserApiService provideUserApiService(Retrofit retrofit) {
        return retrofit.create(UserApiService.class);
    }

    /**
     * 获取Sp
     * @param context
     * @return
     */
    @Provides
    @Singleton
    public SharedPreferences provideSharedPreferences(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    @Provides
    public UserManager provideUserManager(SharedPreferences preferences, UserApiService service) {
        return new UserManager(preferences, service);
    }

    @Provides
    public PasswordValidator providePasswordValidator() {
        return new PasswordValidator();
    }

    @Provides
    public DaggerPresenter provideLoginPresenter(UserManager userManager, PasswordValidator validator) {
        return new DaggerPresenter(userManager, validator);
    }

    @Provides
    public Context provideContext() {
        return mContext;
    }
}
